'''
HASSMART Cover v0.5
by Jones
2018-10-14
'''
import time
import socket
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv

from threading import Thread, Event
from homeassistant.components.cover import (CoverDevice, DOMAIN, ATTR_POSITION, PLATFORM_SCHEMA)
from homeassistant.const import (ATTR_ATTRIBUTION, CONF_HOST, EVENT_HOMEASSISTANT_STOP)
from homeassistant.helpers.event import track_utc_time_change

_LOGGER = logging.getLogger(__name__)
log=_LOGGER.warning
err=_LOGGER.error

HS_COVER_TCP_PORT = 8899
HS_COVER_DIRECTION = 'default'

SOCKET_BUFSIZE = 1024
SOCKET_TIMEOUT = 30.0
DISCOVER_TIMEOUT = 20

ATTRIBUTION = 'A HASSMART Product'

CONF_PORT = 'port'
CONF_DIRECTION = 'direction'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_HOST): cv.string,
    vol.Optional(CONF_PORT, default = HS_COVER_TCP_PORT): cv.port,
    vol.Optional(CONF_DIRECTION, default = HS_COVER_DIRECTION): vol.In(['default', 'reverse']),
})




def iif(condition, true_part, false_part):  
    return (condition and [true_part] or [false_part])[0]

auchCRCHi = [
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 
]
auchCRCLo = [ 
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 
0x07, 0xC7, 0x05, 0x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
0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 
0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 
0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 
0x43, 0x83, 0x41, 0x81, 0x80, 0x40 
]

def crc16(puchMsg,l):
        
        uchCRCHi = 0xFF
        uchCRCLo = 0xFF
        uIndex = 0
        usDataLen=l
        a=[]
        while usDataLen>0:
              uIndex = uchCRCHi^puchMsg[l-usDataLen]
              uchCRCHi = uchCRCLo^auchCRCHi[uIndex]
              uchCRCLo = auchCRCLo[uIndex]	
              usDataLen=usDataLen-1

        a.append(uchCRCHi)
        a.append(uchCRCLo)
        return a


def hex(v):#十进制转16进制
    return ("%02X"%v)
    
def dec(v):#16进制转10进制
    return int(v, 16)
    
def binn(hexxx,bittt):#16进制转二进制  并返回指定位是 0 还是 1  
    b=bin(int(hexxx,16))[2:].rjust(8,"0")
    return(b[-(bittt+1)])

def hex2bit(hexxx):#
   if hexxx == "01":return "10"
   if hexxx == "02":return "20"
   if hexxx == "04":return "30"
   if hexxx == "08":return "40"
   if hexxx == "10":return "50"
   if hexxx == "20":return "60"

   
def Hexs2Decs(hexstr):#
   
     a = hexstr.split(' ')
     for i in range(len(a)):
       a[i] = int(a[i], 16)
   
     a = a + crc16(a,len(a)) 
     return  bytes(a)










class HASSmartHub(object):
    '''hassmart hub init'''
    def __init__(self, tcp_ip, tcp_port, direction):
        self._tcp_ip = tcp_ip
        self._tcp_port = tcp_port
        self._conf_motor_direction = direction
        self._socket = None
        self._timeout_number = 0
        self._check_state = False
        self._threads = []
        self.thread_event = Event()
        self.callbacks = None
        log("self.callbacks = None")
        self.position = None

        self.motor_status = None
        self.motor_direction = None
        self.motor_manual_start = None

        self.is_closing = None
        self.is_opening = None
        self.is_closed = True

        self.listen()

    def check_cover_state(self):#检测窗帘是否在线 这里没有重连的操作
        self._check_state = True#注意 这个函数仅在启动时运行一次
        if self._check_socket():#假如有通讯号
            time_now = time.time()
            while self._check_state:
                time.sleep(1)
                if time.time() - time_now > DISCOVER_TIMEOUT:#20秒内必须要有响应 
                    self._check_state = False
                    _LOGGER.error('no hassmart cover response')
                    return False

            if self.motor_direction != self._conf_motor_direction:
                log('changing motor direction to %s', self._conf_motor_direction)
                self.set_motor_direction(self._conf_motor_direction)
            return True
        else:
            return False

    def _create_socket(self):
        if self._socket is not None:
            self._socket.close()
            self._socket = None
        log("窗帘正在连接....")
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._socket.settimeout(SOCKET_TIMEOUT)
        try:
            self._socket.connect((self._tcp_ip, self._tcp_port))
            log("窗帘连接成功")
        except Exception as e:
            _LOGGER.error('creat socket error %s', e)

    def _check_socket(self):#检测是否有通讯号 如果有 那就说明连接成功
        try:
            peer = self._socket.getpeername()
            return True
        except Exception as e:
            _LOGGER.info('not connected: %s', e)
            return False

    def _send_packet(self, data):
        try:
            self._socket.send(data)
            log("发送到窗帘: %s", data)
        except Exception as e:
            _LOGGER.error('send packet error: %s, recreating socket...', e)
            self._create_socket()

    def listen(self):#开始连接 并监听
        self._create_socket()
        if self._check_socket():
            self.thread_event.set()#如果连接成功 就分配一个线程专门负责网络数据的接收
        else:
            _LOGGER.error('1st creating socket error, recreating...')
            self._create_socket()
        thread_listen = Thread(target = self._handle_recv_data, args = ())
        self._threads.append(thread_listen)
        thread_listen.daemon = True
        thread_listen.start()
        self.get_position()

    def stop_listen(self):
        self.thread_event.clear()
        if self._socket is not None:
            _LOGGER.info('Closing socket')
            self._socket.close()
            self._socket = None
        for thread in self._threads:
            thread.join()

    def _handle_recv_data(self):#实时接收 IP发过来的数据包
        #self.thread_event.wait()
        while self.thread_event.is_set():
            if self._timeout_number > 1:
                _LOGGER.error("timeout > 1, recreating socket")
                self._create_socket()
                self._timeout_number = 0
            try:
                data = self._socket.recv(SOCKET_BUFSIZE)
                t="%02X %02X %02X %02X %02X %02X %02X"%(data[0],data[1],data[2],data[3],data[4],data[5],data[6])
                log("窗帘接收="+t)
            # except socket.timeout:
            except Exception as e:
                _LOGGER.error("recv data error: %s", e)
                self._timeout_number += 1
                continue

            if not data:
                self._create_socket()# 55 FE FE 01 02 01 pos 82 48
                return False
            else:
               if self._check_state:
                 self._check_state = False   # 这是启动后的第一次也是最后一次数据包
                 continue
               self.callbacks(data)#对接收到的数据进行解析
        log("线程结束")    

    def get_position(self):#55 FE FE 01 02 01 85 42
        packet = Hexs2Decs("55 FE FE 01 02 01")#b"\x55\xfe\xfe\x03\x01\xb9\x24"
        self._send_packet(packet)

    def open_cover(self):#55 FE FE 03 01 B9 24
        packet = Hexs2Decs("55 FE FE 03 01")#b"\x55\xfe\xfe\x03\x01\xb9\x24"
        self._closed = False
        self._send_packet(packet)

    def close_cover(self):#55 FE FE 03 02 F9 25
        packet = packet = Hexs2Decs("55 FE FE 03 02")#b"\x55\xfe\xfe\x03\x02\xf9\x25"
        self._closed = True
        self._send_packet(packet)

    def stop_cover(self):
        packet = packet = Hexs2Decs("55 FE FE 03 03")#b"\x55\xfe\xfe\x03\x03\x38\xe5"
        self._send_packet(packet)

    def set_cover_position(self, position):
        packet = Hexs2Decs("55 FE FE 03 04 " + hex(position))
        self._send_packet(packet)

    def set_motor_direction(self, direction):
        if direction == 'default':
            packet = b"\x15\x00"
        elif direction == 'reverse':
            packet = b"\x15\x01"
        self._send_packet(packet)

def setup_platform(hass, config, add_devices, discovery_info = None):#程序的主入口
    """Set up hassmart cover platform"""
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    direction = config.get(CONF_DIRECTION)

    hub = HASSmartHub(host, port, direction)#所有的实例 他的连接方法只有一个  这里进行了一次网络连接

    def stop_listening(event):
        _LOGGER.info('closing hassmart socket...')
        hub.stop_listen()

    if hub.check_cover_state():#假如连接成功
        host = 'hassmart_' + '_'.join(host.split('.'))
        add_devices([HASSmartCover(hass, host, hub)])
        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_listening)#????
        return True
    else:
        hub.thread_event.clear()
        hub.stop_listen()
        return False

class HASSmartCover(CoverDevice):#这个是官方提供的SDK
    def __init__(self, hass, name, hub):
        self._name = name
        self._hass = hass
        self._unique_id = name
        
        self._closed = hub.is_closed
        self._is_opening = hub.is_opening
        self._is_closing = hub.is_closing

        self._motor_direction = hub.motor_direction
        self._motor_manual_start = hub.motor_manual_start

        self._set_position_value = None
        self._unsub_listener_cover = None

        self._position = hub.position
        self._open_cover = hub.open_cover
        self._close_cover = hub.close_cover
        self._stop_cover = hub.stop_cover
        self._get_position = hub.get_position
        self._set_position = hub.set_cover_position
        self._set_direction = hub.set_motor_direction

        hub.callbacks = self._process_data
        log("hub.callbacks = self._process_data")

        self._heart_beat()#设置心跳




#读当前位置         55 fe fe 01 02 01 
#返回#           55 FE FE 01 02 01 pos 82 48

#主动反馈
#55 FE FE 04 02 08 起拉位置 00 00 状态位 00 00 00 01 EC 0B 
#55 FE FE 04 02 08 结束位置 00 00 状态位 00 00 00 01 17 DC 
#6位置范围: 00-64
#9状态位: 01 打开
#        02 关闭
#        00 停止


    def _process_data(self, data):#对窗帘返回的数据进行解析
        ''' handle position & motor status '''
        # 55 FE FE 01 02 01 pos 82 48
        

        try:
           log("窗帘接收数据长度="+str(len(data)))
           if (len(data))>9:#下面是主动发送的
            if data[9] == 0x00:
                self._is_opening = False
                self._is_closing = False
            elif data[9] == 0x01:
                self._is_opening = True
                self._is_closing = False
            elif data[9] == 0x02:
                self._is_opening = False
                self._is_closing = True
            else:
                pass

           if (data[3] == 0x04 and  data[4] == 0x02 and data[5] == 0x08) or  (data[3] == 0x01 and  data[4] == 0x02 and data[5] == 0x01) :
                self._position = int(data[6])
                log('接收窗帘位置'+str(self._position))
                if  self.current_cover_position == 0:
                   self._closed = True
                else:
                   self._closed = False
                self.schedule_update_ha_state()
        except Exception as e:
         err(str(e))

    @property
    def name(self):
        """Return the name of the cover."""
        return "卧室窗帘" + str(self._position) + "%"

    @property
    def unique_id(self):
        return self._unique_id

    @property
    def should_poll(self):
        """No polling needed for a cover."""
        return False

    @property
    def current_cover_position(self):
        """Return the current position of the cover."""
        return self._position

    @property
    def is_closed(self):
        """Return if the cover is closed."""
        return self._closed

    @property
    def is_opening(self):
        """Return if the cover is opening."""
        return self._is_opening

    @property
    def is_closing(self):
        """Return if the cover is closing."""
        return self._is_closing

    @property
    def device_state_attributes(self):
        if self._position is not None:
            return {
                'motor_direction': self._motor_direction,
                'motor_manual_start': self._motor_manual_start,
                ATTR_ATTRIBUTION: ATTRIBUTION
            }

    def close_cover(self, **kwargs):
        """Close the cover."""
        self._close_cover()
        self.schedule_update_ha_state()

    def open_cover(self, **kwargs):
        """Open the cover."""
        self._open_cover()
        self.schedule_update_ha_state()

    def stop_cover(self, **kwargs):
        """Stop the cover."""
        self._is_closing = False
        self._is_opening = False
        self._stop_cover()

    def set_cover_position(self, **kwargs):
        """Move the cover to a specific position."""
        position = kwargs.get(ATTR_POSITION)
        self._set_position_value = position
        self._set_position(position)

    def set_motor_direction(self, direction):
        self._set_direction(direction)

    def _heart_beat(self):
        track_utc_time_change(self._hass, self._handle_heart_beat, second = range(0, 60, 20))

    def _handle_heart_beat(self, now):
        self._get_position()#请求获取当前位置 假如通讯失败  那么自动重连
        if  self.current_cover_position == 0:
         self._closed = True
        else:
         self._closed = False
        self.schedule_update_ha_state()
       
